#include "key.h"
#include "init.h"


static bool key_is_pressing;

void key_init(void)
{
    /** 
     * TODO: 
     * if io used for key
     * please pull up or down, avoid it jump
     * */
    // _P04_IO_PULLUP();
}

void key_handle_10ms(void)
{
#if (CONFIG_KEY_LONG_PRESS_CNT >= 255)
    static uint16_t key_0_pressed_cnt;
#else
    static uint8_t key_0_pressed_cnt;
#endif
    static bool key_prev_status;

    if (!(key_prev_status ^ CONFIG_KEY_IO_STATUS)) {
    #if (CONFIG_KEY_ACTIVE_LOW == 1)
        if (key_prev_status == 0) {
    #else
        if (key_prev_status == 1) {
    #endif
            key_is_pressing = true;
        } else {
            key_is_pressing = false;
        }
    }
    
    key_prev_status = CONFIG_KEY_IO_STATUS;
    /*
     * deal with key
     */
    if (key_is_pressing) {
    #if (CONFIG_KEY_LONG_PRESS_CNT >= 255)
            key_0_pressed_cnt++;
    #else
        if (key_0_pressed_cnt < 255)
            key_0_pressed_cnt++;
    #endif
    } else {
        if ((key_0_pressed_cnt < CONFIG_KEY_SHORT_PRESS_CNT) && (key_0_pressed_cnt > 2)) {
            /* recognize to SHORT PRESS */
            event_set_ui(EVENT_UI_KEY_CLICK);
        }
        key_0_pressed_cnt = 0;
    }
   
    if (key_0_pressed_cnt == CONFIG_KEY_2S_PRESS_CNT) {
        event_set_ui(EVENT_UI_KEY_LONGPRESS_2S);
        key_0_pressed_cnt = CONFIG_KEY_2S_PRESS_CNT + 1;
    }

}


